﻿Imports EstoqueBLL
Public Class CompraProduto
    Public objpeca As New PECABLL
    Dim mc, m, pc, pv, vu, vt, qtde, icms, ipi, frete, desc As New Decimal
    Dim op As Char = "C"
    Public objitens As ItensCompraBLL
    Public status As String

#Region "Métodos"
#Region "Limpar Campos"
    Sub limpar()
        limpaproduto()
        objitens = Nothing
        objpeca = Nothing
        op = "C"
        status = ""
        mc = 0
        m = 0
        pv = 0
        pc = 0

    End Sub
#End Region

#Region "Carregar Produto"
    Sub Carregaproduto()
        If (Not IsNothing(objpeca)) Then
            TDescProduto.Text = objpeca.pro_descricao
            TCReal.Text = objpeca.pro_precocusto
            TPVenda.Text = objpeca.pro_precovenda
            TMargem.Text = objpeca.pec_margem
            TMC.Text = objpeca.pec_mcontrib
            TCodBarras.Text = objpeca.pec_codbarra
        End If

    End Sub
#End Region

#Region "limpa produto"
    Sub limpaproduto()
        TCodBarras.Text = ""
        TDescProduto.Text = ""
        TQtde.Text = 1
        TVUnitario.Text = "0,00"
        TDesconto.Text = "0,00"
        TVTotal.Text = "0,00"
        TIcms.Text = "0,00"
        TIpi.Text = "0,00"
        TCReal.Text = "0,00"
        TMargem.Text = "0"
        TMC.Text = "0"
        TPVenda.Text = "0,00"
    End Sub
#End Region

#Region "Margem"
    Public Sub calculomargem(prev As Decimal, prec As Decimal)
        Try
            If (prec > 0) Then
                m = (prev - prec) / prec
            End If

            TMargem.Text = FormatPercent(m)
        Catch ex As Exception
            Throw New Exception("Erro ao calcular margem.")
        End Try

    End Sub
#End Region

#Region "MargemContribuição"
    Public Sub calculomargemc(prev As Decimal, prec As Decimal)
        Try

            If (prev > 0) Then

                mc = (prev - prec) / prev
            End If
            TMC.Text = FormatPercent(mc)
        Catch ex As Exception
            Throw New Exception("Erro ao calcular margem de contribuição.")
        End Try
    End Sub
#End Region

#Region "Valor Total"
    Sub valortotal()
        vt = (qtde * vu) - desc
        TVTotal.Text = FormatCurrency(vt)
    End Sub
#End Region

#Region "Custo Real"
    Sub custoreal()
        pc = (icms + ipi + vt) * (1 + frete) / qtde
        TCReal.Text = FormatCurrency(pc)
        TPCusto_LostFocus(Nothing, Nothing)
    End Sub
#End Region

#Region "Preço Venda"
    Public Sub calculoprecovenda(marg As Decimal, margc As Decimal, prec As Decimal)
        Try

            If (op = "M") Then
                pv = (1 + marg) * pc
                TPVenda.Text = FormatCurrency(pv)
            End If
            If (op = "C") Then
                Dim aux1 As Decimal
                aux1 = 1 / (1 - mc)
                pv = pc * aux1
                TPVenda.Text = FormatCurrency(pv)
            End If
        Catch ex As Exception
            Throw New Exception("Erro ao calcular preço de venda.")
        End Try

    End Sub
#End Region

#Region "Verifica Valor Minimo"
    Public Sub verificaminvalor()
        Dim r1, r2, r3, r4, r5, r6 As Boolean
        r1 = Decimal.TryParse(TVUnitario.Text.Replace("R$", ""), vu)
        r2 = Decimal.TryParse(TDesconto.Text.Replace("R$", ""), desc)
        r3 = Decimal.TryParse(TIcms.Text.Replace("R$", ""), icms)
        r4 = (Decimal.TryParse(TIpi.Text.Replace("R$", ""), ipi))
        r5 = Decimal.TryParse(TPorcFrete.Text.Replace("%", ""), frete)
        r6 = Decimal.TryParse(TQtde.Text, qtde)
        custoreal()
    End Sub
#End Region

#Region "Carrega Campos"
    Public Sub Carregacampos(objitens As ItensCompraBLL)
        objpeca = New PECABLL
        Me.objitens = objitens
        objpeca = objpeca.carregaproduto(objitens.pro_codigo)
        TCodBarras.Text = objpeca.pec_codbarra
        TCodBarras_LostFocus(Nothing, Nothing)
        TDescProduto.Text = objpeca.pro_descricao
        TQtde.Text = objitens.itc_qtde
        TVUnitario.Text = objitens.itc_valorunitario
        TVTotal.Text = objitens.itc_valortotal
        TDesconto.Text = objitens.itc_desconto
        TIcms.Text = objitens.itc_substtrib
        TIpi.Text = objitens.itc_ipi
        TCReal.Text = objitens.itc_custoreal
        TMC.Text = objitens.itc_margcontrib
        TMargem.Text = objitens.itc_porcentagem
        TPVenda.Text = objitens.itc_precovenda
        TPorcFrete.Text = FormatPercent(objitens.itc_frete / 100)
        TQtde.Focus()
    End Sub
#End Region

#Region "Buscar por codigo de barras"
    Public Sub buscacodbar()
        Dim dt As New DataTable
        objpeca = New PECABLL
        dt = objpeca.localizar(TCodBarras.Text, 5)
        If (dt.Rows.Count > 0) Then
            objpeca = New PECABLL(Val(dt.Rows(0)("pec_codigo").ToString))
            Carregaproduto()
            GroupBox1.Enabled = True
        Else
            limpaproduto()
            MessageBox.Show("Peça não cadastrada!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Dim frm As New PecaCON
            frm.tipo = "ret"
            frm.ShowDialog()
            If (Not IsNothing(frm.objprod) And frm.objprod.pec_codigo > 0) Then
                objpeca = frm.objprod
                Carregaproduto()
                GroupBox1.Enabled = True
            Else
                GroupBox1.Enabled = False
            End If

        End If
    End Sub
#End Region

#End Region

#Region "Eventos"
#Region "KeyDown Form"

    Private Sub CompraProduto_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If status = "E" Then
            objitens = Nothing
            objpeca = Nothing
        End If

    End Sub
    Private Sub CompraProdutoCAD_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If (e.KeyCode = Keys.Enter) Then
            SendKeys.Send("{TAB}")
        End If
        If (e.KeyCode = Keys.Escape) Then
            Me.Close()
        End If
    End Sub
#End Region

#Region "TPCusto_LostFocus"
    Private Sub TPCusto_LostFocus(sender As Object, e As System.EventArgs) Handles TCReal.LostFocus
        Try
            Dim r, r1, r2, r3 As New Boolean
            pc = m = mc = pv = 0

            r = Decimal.TryParse(TCReal.Text.ToString.Replace("R$", ""), pc)
            r1 = Decimal.TryParse(TMargem.Text.ToString.Replace("%", ""), m)
            r2 = Decimal.TryParse(TMC.Text.ToString.Replace("%", ""), mc)
            r3 = Decimal.TryParse(TPVenda.Text.ToString.Replace("R$", ""), pv)

            TCReal.Text = FormatCurrency(pc)
            m = m / 100
            mc = mc / 100
            'colocar metodos de calculos
            If (pc > 0) Then
                calculoprecovenda(m, mc, pc)
                calculomargem(pv, pc)
                calculomargemc(pv, pc)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub
#End Region

#Region "TPMargem_LostFocus"
    Private Sub TMargem_LostFocus(sender As Object, e As System.EventArgs) Handles TMargem.LostFocus
        'TMargem.Text = FormatPercent(TMargem.Text)
        op = "M"
        TPCusto_LostFocus(Nothing, Nothing)
    End Sub
#End Region

#Region "TPMargemC_LostFocus"
    Private Sub TMC_LostFocus(sender As Object, e As System.EventArgs) Handles TMC.LostFocus
        'TMC.Text = FormatPercent(TMC.Text)
        op = "C"
        Dim r2 As Boolean
        Dim marg As Decimal
        r2 = Decimal.TryParse(TMC.Text.ToString.Replace("%", ""), marg)
        If (Not marg / 100 >= 1) Then
            TPCusto_LostFocus(Nothing, Nothing)
        Else
            MessageBox.Show("A margem de contribuição tem que variar de 0 - 100%!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            TMC.Text = ""
            TMC.Focus()
        End If
    End Sub
#End Region

#Region "TPVenda_LostFocus"
    Private Sub TPVenda_LostFocus(sender As Object, e As System.EventArgs) Handles TPVenda.LostFocus
        TPVenda.Text = FormatCurrency(TPVenda.Text)
        Try
            Dim r, r1, r2, r3 As New Boolean
            pc = m = mc = pv = 0

            r = Decimal.TryParse(TCReal.Text.Replace("R$", ""), pc)
            r1 = Decimal.TryParse(TMargem.Text.Replace("%", ""), m)
            r2 = Decimal.TryParse(TMC.Text.Replace("%", ""), mc)
            r3 = Decimal.TryParse(TPVenda.Text.Replace("R$", ""), pv)
            If (True = r) Then
                m = m / 100
                mc = mc / 100
                'colocar metodos de calculos
                calculomargem(pv, pc)
                calculomargemc(pv, pc)
                If (pc > 0) Then
                    calculoprecovenda(m, mc, pc)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
        TMC.Text = FormatPercent(mc)
        TMargem.Text = FormatPercent(m)
        TPVenda.Text = FormatCurrency(pv)
    End Sub
#End Region

#Region "Botão Gravar"
    Private Sub TSBGravar_Click(sender As System.Object, e As System.EventArgs) Handles TSBGravar.Click
        Try
            If (Not IsNothing(objpeca)) Then
                If objpeca.pro_codigo > 0 Then
                    TQtde_LostFocus(Nothing, Nothing)
                    objitens = New ItensCompraBLL
                    objitens.itc_custoreal = Decimal.Parse(TCReal.Text.Replace("$", "").Replace("R", ""))
                    objitens.itc_frete = Decimal.Parse(TPorcFrete.Text.Replace("%", ""))
                    objitens.itc_ipi = Decimal.Parse(TIpi.Text.Replace("$", "").Replace("R", ""))
                    objitens.itc_margcontrib = Decimal.Parse(TMC.Text.Replace("%", ""))
                    objitens.itc_porcentagem = Decimal.Parse(TMargem.Text.Replace("%", ""))
                    objitens.itc_qtde = Decimal.Parse(TQtde.Text)
                    objitens.itc_substtrib = Decimal.Parse(TIcms.Text.Replace("$", "").Replace("R", ""))
                    objitens.itc_valortotal = Decimal.Parse(TVTotal.Text.Replace("$", "").Replace("R", ""))
                    objitens.itc_valorunitario = Decimal.Parse(TVUnitario.Text.Replace("$", "").Replace("R", ""))
                    objitens.itc_precovenda = Decimal.Parse(TPVenda.Text.Replace("$", "").Replace("R", ""))
                    objitens.itc_desconto = Decimal.Parse(TDesconto.Text.Replace("$", "").Replace("R", ""))
                    objitens.pro_codigo = objpeca.pro_codigo
                    status = "O"
                    Me.Close()
                End If
            End If
        Catch ex As Exception
            MessageBox.Show("Erro ao gravar")
        End Try
    End Sub
#End Region

#Region "Load"
    Private Sub CompraProduto_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        If status = "E" Then
            'irá alterar...
            Carregacampos(objitens)
            GroupBox1.Enabled = True
            TQtde_LostFocus(Nothing, Nothing)
        Else
            limpar()
        End If
    End Sub
#End Region

#Region "TVUnitario_LostFocus"

    Private Sub TVUnitario_LostFocus(sender As Object, e As System.EventArgs) Handles TVUnitario.LostFocus, TIcms.LostFocus, TIpi.LostFocus, TPorcFrete.LostFocus
        Dim r1, r2, r3, r4, r5, r6 As Boolean
        r1 = Decimal.TryParse(TVUnitario.Text.Replace("R$", ""), vu)
        r2 = Decimal.TryParse(TDesconto.Text.Replace("R$", ""), desc)
        r3 = Decimal.TryParse(TIcms.Text.Replace("R$", ""), icms)
        r4 = (Decimal.TryParse(TIpi.Text.Replace("R$", ""), ipi))
        r5 = Decimal.TryParse(TPorcFrete.Text.Replace("%", ""), frete)
        r6 = Decimal.TryParse(TQtde.Text, qtde)

        frete = frete / 100
        valortotal()
        custoreal()
        TDesconto.Text = FormatCurrency(desc)
        TIcms.Text = FormatCurrency(icms)
        TIpi.Text = FormatCurrency(ipi)
        TPorcFrete.Text = FormatPercent(frete)
        TVUnitario.Text = FormatCurrency(vu)
        TCReal.Text = FormatCurrency(pc)
    End Sub

    Private Sub TDesconto_LostFocus(sender As Object, e As System.EventArgs) Handles TDesconto.LostFocus

        Dim r1, r2, r3, r4, r5, r6 As Boolean
        r1 = Decimal.TryParse(TVUnitario.Text.Replace("R$", ""), vu)
        r2 = Decimal.TryParse(TDesconto.Text.Replace("R$", ""), desc)
        r3 = Decimal.TryParse(TIcms.Text.Replace("R$", ""), icms)
        r4 = (Decimal.TryParse(TIpi.Text.Replace("R$", ""), ipi))
        r5 = Decimal.TryParse(TPorcFrete.Text.Replace("%", ""), frete)
        r6 = Decimal.TryParse(TQtde.Text, qtde)
        If (desc <= (qtde * vu)) Then
            frete = frete / 100
            valortotal()
            custoreal()
            TDesconto.Text = FormatCurrency(desc)
            TIcms.Text = FormatCurrency(icms)
            TIpi.Text = FormatCurrency(ipi)
            TPorcFrete.Text = FormatPercent(frete)
            TVUnitario.Text = FormatCurrency(vu)
            TCReal.Text = FormatCurrency(pc)
        Else
            MessageBox.Show("O desconto não pode ser maior que o valor total", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            TDesconto.Focus()

        End If

    End Sub
#End Region

#Region "Keypress"
    Private Sub TCodBarras_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TCodBarras.KeyPress
        If Not (Char.IsNumber(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True
        If (e.KeyChar = Convert.ToChar(Keys.Return)) Then

        End If
    End Sub

    Private Sub TVUnitario_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TVUnitario.KeyPress, TVTotal.KeyPress, TPVenda.KeyPress, TPorcFrete.KeyPress, TMC.KeyPress, TMargem.KeyPress, TIpi.KeyPress, TIcms.KeyPress, TDesconto.KeyPress, TCReal.KeyPress
        If Not (Char.IsNumber(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True
        Dim obj As New TextBox
        obj = sender
        If (sender.Text.Contains(",") = False And e.KeyChar = ",") Then e.Handled = False

    End Sub
    Private Sub TQtde_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TQtde.KeyPress
        If Not (Char.IsNumber(e.KeyChar) Or Char.IsControl(e.KeyChar)) Then e.Handled = True


    End Sub
#End Region

#Region "Botão Busca Produto"
    Private Sub BBuscaProduto_Click(sender As System.Object, e As System.EventArgs) Handles BBuscaProduto.Click
        Dim frm As New PecaCON
        frm.tipo = "ret"
        frm.ShowDialog()
        If (Not IsNothing(frm.objprod) And frm.objprod.pec_codigo > 0) Then
            objpeca = frm.objprod
            Carregaproduto()
            GroupBox1.Enabled = True
        Else : GroupBox1.Enabled = False
        End If
    End Sub
#End Region

#Region "Voltar"
    Private Sub TSBVoltar_Click(sender As System.Object, e As System.EventArgs) Handles TSBVoltar.Click
        Me.Close()
    End Sub
#End Region

#Region "Tqte.lostfocus"
    Private Sub TQtde_LostFocus(sender As Object, e As System.EventArgs) Handles TQtde.LostFocus
        Dim r1, r2, r3, r4, r5, r6 As Boolean
        r1 = Decimal.TryParse(TVUnitario.Text.Replace("R$", ""), vu)
        r2 = Decimal.TryParse(TDesconto.Text.Replace("R$", ""), desc)
        r3 = Decimal.TryParse(TIcms.Text.Replace("R$", ""), icms)
        r4 = (Decimal.TryParse(TIpi.Text.Replace("R$", ""), ipi))
        r5 = Decimal.TryParse(TPorcFrete.Text.Replace("%", ""), frete)
        r6 = Decimal.TryParse(TQtde.Text, qtde)
        If (qtde > 0) Then
            frete = frete / 100
            valortotal()
            custoreal()
            TDesconto.Text = FormatCurrency(desc)
            TIcms.Text = FormatCurrency(icms)
            TIpi.Text = FormatCurrency(ipi)
            TPorcFrete.Text = FormatPercent(frete)
            TVUnitario.Text = FormatCurrency(vu)
            TCReal.Text = FormatCurrency(pc)
        Else
                MessageBox.Show("Quantidade não pode ser menor que 1", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                TQtde.Focus()
            End If

    End Sub
#End Region
#End Region

    Private Sub TCodBarras_LostFocus(sender As Object, e As System.EventArgs) Handles TCodBarras.LostFocus
        If (IsNothing(objpeca)) Then
            If Val(TCodBarras.Text) > 0 Then
                buscacodbar()
                TQtde.Focus()
            End If
        End If

    End Sub

End Class